const { createApp } = Vue;

createApp({
    data() {
        return {
            avatarUrl: '',
            frames: (() => {
                const frames = [
                    { id: 'none', preview: '', name: '无框', selected: true }
                ];
                
                for (let i = 1; i <=26; i++) {
                    frames.push({
                        id: `frame${i}`,
                        preview: `images/plan${i}.png`,
                        name: `头像框 ${i}`,
                        selected: false
                    });
                }
                return frames;
            })(),
            defaultAvatars: [
                { 
                    id: 'avatar1', 
                    url: 'images/user.jpeg',
                    name: '默认头像1',
                    fallback: 'https://via.placeholder.com/200x200/3498db/ffffff?text=头像1'
                }
                // { 
                //     id: 'avatar2', 
                //     url: 'images/user2.webp',
                //     name: '默认头像2', 
                //     fallback: 'https://via.placeholder.com/200x200/e74c3c/ffffff?text=头像2'
                // },
                // { 
                //     id: 'avatar3', 
                //     url: 'images/user3.webp',
                //     name: '默认头像3',
                //     fallback: 'https://via.placeholder.com/200x200/2ecc71/ffffff?text=头像3'
                // }
            ],
            selectedFrame: 'none',
            tempFilePaths: {},
            canvas: null,
            ctx: null,
            isLoading: false
        }
    },
    
    mounted() {
        this.initCanvas();
        this.drawDefaultAvatar();
        this.bindEvents();
        this.preloadImages();
    },
    
    methods: {
        initCanvas() {
            this.canvas = document.getElementById('avatarCanvas');
            if (!this.canvas) {
                console.error('Canvas元素未找到');
                return;
            }
            this.ctx = this.canvas.getContext('2d');
            this.canvas.width = 400; // 提高分辨率
            this.canvas.height = 400;
        },
        
        bindEvents() {
            // 绑定上传按钮事件
            const chooseBtn = document.getElementById('chooseAvatar');
            const uploadInput = document.getElementById('avatarUpload');
            
            if (chooseBtn && uploadInput) {
                chooseBtn.addEventListener('click', () => {
                    uploadInput.click();
                });
                
                uploadInput.addEventListener('change', this.handleFileUpload);
            }
            
            // 绑定保存和重置按钮事件
            const saveBtn = document.getElementById('saveAvatar');
            const resetBtn = document.getElementById('resetAvatar');
            
            if (saveBtn) saveBtn.addEventListener('click', this.saveAvatar);
            if (resetBtn) resetBtn.addEventListener('click', this.resetAvatar);
        },
        
        async preloadImages() {
            // 预加载头像框图片
            for (let frame of this.frames) {
                if (frame.id !== 'none') {
                    await this.preloadImage(frame.preview);
                }
            }
        },
        
        preloadImage(src) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => resolve(img);
                img.onerror = reject;
                img.src = src;
            });
        },
        
        handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                alert('请选择图片文件！');
                return;
            }
            
            // 检查文件大小（限制为5MB）
            if (file.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过5MB！');
                return;
            }
            
            this.isLoading = true;
            const reader = new FileReader();
            
            reader.onload = (e) => {
                this.avatarUrl = e.target.result;
                this.drawAvatarWithFrame();
                this.isLoading = false;
            };
            
            reader.onerror = () => {
                alert('图片读取失败，请重试！');
                this.isLoading = false;
            };
            
            reader.readAsDataURL(file);
            
            // 重置文件输入，允许选择同一文件
            event.target.value = '';
        },
        
        selectDefaultAvatar(avatarId) {
            const selectedAvatar = this.defaultAvatars.find(avatar => avatar.id === avatarId);
            
            if (selectedAvatar) {
                this.isLoading = true;
                
                // 首先尝试加载本地图片
                const img = new Image();
                img.onload = () => {
                    this.avatarUrl = selectedAvatar.url;
                    this.drawAvatarWithFrame();
                    this.isLoading = false;
                };
                
                img.onerror = () => {
                    // 如果本地图片加载失败，使用备用网络图片
                    console.warn(`本地图片 ${selectedAvatar.url} 加载失败，使用备用图片`);
                    this.avatarUrl = selectedAvatar.fallback;
                    this.drawAvatarWithFrame();
                    this.isLoading = false;
                };
                
                img.src = selectedAvatar.url;
            }
        },
        
        handleImageError(event) {
            const img = event.target;
            const avatarItem = img.closest('.avatar-item');
            if (avatarItem) {
                const avatarId = Array.from(avatarItem.parentNode.children).indexOf(avatarItem);
                const fallbackUrl = this.defaultAvatars[avatarId]?.fallback;
                if (fallbackUrl) {
                    img.src = fallbackUrl;
                }
            }
        },
        
        handleFrameError(event) {
            console.warn('头像框图片加载失败:', event.target.src);
        },
        
        selectFrame(frameId) {
            this.selectedFrame = frameId;
            if (this.avatarUrl) {
                this.drawAvatarWithFrame();
            }
        },
        
        drawDefaultAvatar() {
            if (!this.ctx) return;
            
            const ctx = this.ctx;
            const width = this.canvas.width;
            const height = this.canvas.height;
            
            ctx.clearRect(0, 0, width, height);
            
            // 绘制渐变背景
            const gradient = ctx.createLinearGradient(0, 0, width, height);
            gradient.addColorStop(0, '#34495e');
            gradient.addColorStop(1, '#2c3e50');
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, width, height);
            
            // 绘制边框
            ctx.strokeStyle = '#ecf0f1';
            ctx.lineWidth = 4;
            ctx.strokeRect(2, 2, width - 4, height - 4);
            
            // 绘制默认头像图标
            ctx.fillStyle = '#ecf0f1';
            ctx.font = 'bold 40px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('👤', width/2, height/2 - 10);
            
            // 绘制提示文字
            ctx.font = '16px Arial';
            ctx.fillStyle = '#bdc3c7';
            ctx.fillText('头像', width/2, height/2 + 30);
        },
        
        drawAvatarWithFrame() {
            if (!this.avatarUrl) {
                this.drawDefaultAvatar();
                return;
            }
            
            if (!this.ctx) return;
            
            const ctx = this.ctx;
            const canvasWidth = this.canvas.width;
            const canvasHeight = this.canvas.height;
            
            ctx.clearRect(0, 0, canvasWidth, canvasHeight);
            
            const avatarImg = new Image();
            avatarImg.crossOrigin = 'anonymous';
            
            avatarImg.onload = () => {
                // 绘制头像（居中裁剪）
                const avatarSize = Math.min(avatarImg.width, avatarImg.height);
                const sx = (avatarImg.width - avatarSize) / 2;
                const sy = (avatarImg.height - avatarSize) / 2;
                
                ctx.drawImage(avatarImg, sx, sy, avatarSize, avatarSize, 0, 0, canvasWidth, canvasHeight);
                
                // 绘制头像框
                if (this.selectedFrame !== 'none') {
                    const selectedFrame = this.frames.find(frame => frame.id === this.selectedFrame);
                    
                    if (selectedFrame && selectedFrame.preview) {
                        const frameImg = new Image();
                        frameImg.crossOrigin = 'anonymous';
                        
                        frameImg.onload = () => {
                            ctx.drawImage(frameImg, 0, 0, canvasWidth, canvasHeight);
                        };
                        
                        frameImg.onerror = () => {
                            console.error('头像框图片加载失败:', selectedFrame.preview);
                        };
                        
                        frameImg.src = selectedFrame.preview;
                    }
                }
            };
            
            avatarImg.onerror = () => {
                console.error('头像图片加载失败');
                this.drawDefaultAvatar();
            };
            
            avatarImg.src = this.avatarUrl;
        },
        
        saveAvatar() {
            if (!this.avatarUrl) {
                alert('请先选择头像！');
                return;
            }
            
            if (this.isLoading) {
                alert('图片正在加载中，请稍候...');
                return;
            }
            
            try {
                // 创建高分辨率副本用于下载
                const tempCanvas = document.createElement('canvas');
                const tempCtx = tempCanvas.getContext('2d');
                tempCanvas.width = 800;
                tempCanvas.height = 800;
                
                // 绘制头像到临时canvas
                const avatarImg = new Image();
                avatarImg.onload = () => {
                    // 绘制头像
                    const avatarSize = Math.min(avatarImg.width, avatarImg.height);
                    const sx = (avatarImg.width - avatarSize) / 2;
                    const sy = (avatarImg.height - avatarSize) / 2;
                    
                    tempCtx.drawImage(avatarImg, sx, sy, avatarSize, avatarSize, 0, 0, 800, 800);
                    
                    // 绘制头像框
                    if (this.selectedFrame !== 'none') {
                        const selectedFrame = this.frames.find(frame => frame.id === this.selectedFrame);
                        if (selectedFrame && selectedFrame.preview) {
                            const frameImg = new Image();
                            frameImg.onload = () => {
                                tempCtx.drawImage(frameImg, 0, 0, 800, 800);
                                
                                // 保存图片
                                tempCanvas.toBlob((blob) => {
                                    const url = URL.createObjectURL(blob);
                                    const a = document.createElement('a');
                                    a.href = url;
                                    a.download = `中南民族大学校庆头像_${new Date().getTime()}.png`;
                                    document.body.appendChild(a);
                                    a.click();
                                    document.body.removeChild(a);
                                    URL.revokeObjectURL(url);
                                    
                                    alert('头像保存成功！');
                                }, 'image/png', 0.95);
                            };
                            frameImg.src = selectedFrame.preview;
                        }
                    } else {
                        // 没有头像框的情况
                        tempCanvas.toBlob((blob) => {
                            const url = URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            a.download = `中南民族大学校庆头像_${new Date().getTime()}.png`;
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                            URL.revokeObjectURL(url);
                            
                            alert('头像保存成功！');
                        }, 'image/png', 0.95);
                    }
                };
                
                avatarImg.src = this.avatarUrl;
                
            } catch (error) {
                console.error('保存头像失败:', error);
                alert('保存失败，请重试！');
            }
        },
        
        resetAvatar() {
            this.avatarUrl = '';
            this.selectedFrame = 'none';
            this.drawDefaultAvatar();
            
            // 重置文件输入
            const uploadInput = document.getElementById('avatarUpload');
            if (uploadInput) {
                uploadInput.value = '';
            }
        }
    }
}).mount('.container');